package com.wcy.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.wcy.service.IPermissionService;
import com.wcy.util.PasswordUtil;
import com.wcy.util.vo.AuthRequest;
import com.wcy.util.vo.AuthResponse;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("auth")
public class AuthorizeController {
    @Resource
    private IPermissionService permissionService;

    @PostMapping("perms")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<List<String>> getPermissionsByRoleList(@RequestBody List<Object> objs) {
        System.out.println(objs);
        if(objs.size()!=2){
            return ResponseEntity.ok(new ArrayList<>());
        }
        AuthRequest authRequest = new AuthRequest((Map)objs.get(0));
        AuthResponse response = new AuthResponse((Map)objs.get(1));
        if(response.getUser() == null || response.getUser().getRoles() == null || !PasswordUtil.isBCryptEncoded(response.getUser().getValidateToken()) || !PasswordUtil.verifyPassword(authRequest.getRandomCode(), response.getUser().getValidateToken()))
            return ResponseEntity.ok(new ArrayList<>());
        List<String> permissions = permissionService.getPermissionsByRoleList(response.getUser().getRoles());
        return ResponseEntity.ok(permissions);
    }
}
